import win32clipboard
import win32con
import time
import io
from PIL import Image
import os
from datetime import datetime
import uuid
import addnodetofile
import tkinter as tk
import userinput2
import threading
# import orc2
# import orc1
import orc4
import traceback

root=None
def image2png(image):
    png_image_data = io.BytesIO()
    # 将图像保存到新的BytesIO对象中，指定格式为'PNG'
    image.save(png_image_data, format='PNG')
    # png_image_bytes = png_image_data.getvalue()
    return Image.open(png_image_data)

def generate_random_id():
    # 生成一个 UUID
    random_uuid = uuid.uuid4()
    # 将 UUID 转换为十六进制字符串并取前 16 位
    return random_uuid.hex[:16]
 

# 笔记文件夹
wikipath="E:\\wiki\\wikiob\\a2\\全新"

dic={
    'beforewidth':0,
    "beforeinput":"",
    "windowroot":None
    }

save_folder = f"{wikipath}\\_files"
if not os.path.exists(save_folder):
    os.makedirs(save_folder)

def check_clipboard():
    win32clipboard.OpenClipboard()
    try:
        if win32clipboard.IsClipboardFormatAvailable(win32con.CF_DIB):
            data = win32clipboard.GetClipboardData(win32con.CF_DIB)
            image = Image.open(io.BytesIO(data))
            imagepng=image2png(image)

            currentwidth = imagepng.width
            if currentwidth != dic.get('beforewidth'):
                    save_image(imagepng)
                    # dic.update({'beforewidth':image.width})
                    dic['beforewidth']=imagepng.width
    finally:
        win32clipboard.CloseClipboard()


def successFun(_options):
    print("userinputstr", _options["userInput"])
    orcstr = _options["orcstr"];

    if (_options["userInput"] == None or len(_options["userInput"]) == 0):
        return
    print(f"用户输入的是：{_options['userInput']}")
    list1 = _options["userInput"].split('#')
    list2 = [s for s in list1 if s.strip()]
    firsttag = list2[0]
    # 获取第一个 然后附件名称.canvas保存起来
    file_name = str(int(time.time())) + ".png"
    file_path = os.path.join(save_folder, file_name)
    _options["image"].save(file_path)
    print(f"已成功将图片保存到 {file_path}")


    dic['beforeinput'] = _options["userInput"]
    tagstr = f"{_options['userInput']}#{datetime.now().strftime('%Y年%m月%d日')}"
    _dic = {
        "id": generate_random_id(),
        "type": "text",
        "text": f"{tagstr}\n![[_files/{file_name}]]\n\n\n{orcstr}",
        "styleAttributes": {},
        "x": -220,
        "y": 140,
        "width": _options["image"].width,
        "height": _options["image"].height
    }
    print("_dic", _dic);



    addnodetofile.add_node_to_file(_dic, f"{firsttag}.canvas", wikipath)





def userinputEvent(_value):
    dic["beforeinput"]=_value

def afterShowDialog(dicoptions,img):
    print('------afterShowDialog----')
    # orcstr= orc2.img2text(img)
    # orcstr = orc4.img2text(img)
    # print('ocr识别文字：',orcstr)
    # dicoptions['orcstr']=orcstr


def save_image(img):
    # 加入orc识别
    # orcstr = orc2.img2text(img)
    # print('orcstr', orcstr)
    dicoptions = {"orcstr":""}
    try:
       userinput2.initdialog(dic["windowroot"],
                             {
                                 "title": "请给图片标签",
                                 "image": img,
                                 "defaultValue": dic['beforeinput'],
                             },
                             lambda _options: successFun(_options),
                             userinputEvent,
                             lambda: afterShowDialog(dicoptions, img)
                             )
    except Exception as e:
      stack_trace = traceback.extract_tb(e.__traceback__)
      for frame in stack_trace:
          lineno = frame.lineno  # 获取行号
          print(f"异常发生{frame } 在第{lineno} 行")





def long_running_task():
    while True:
        try:
          check_clipboard()
        except Exception as e:
            print(e)

        time.sleep(1)

def start_task():
    task_thread = threading.Thread(target=long_running_task)
    task_thread.start()

def init():
    print('开始初始化')

    # orcreader=orc1.initReader()
    root = tk.Tk()
    root.withdraw()  # 隐藏主窗口
    dic["windowroot"]=root
    start_task()

    root.mainloop()




init()
